<template>
  <div class="weather-container">
    <div class="weather-info">
      <div v-for="(item, index) in processWeatherData" :key="index">
        <span>{{ item.day }}</span>
        <span>{{ item.date }}</span>
        <span>{{ item.condition }}</span>
        <span>风力 {{ item.wind }}级</span>
      </div>
    </div>
    <div class="weather-chart">
      <v-chart :option="option"></v-chart>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { getIPData, getWeatherData } from '@/API'

// 定义props接收外部传入的天气数据
const props = defineProps({
  weatherData: {
    type: Object,
    default: null,
  },
})

// 计算属性，优先使用外部传入的数据，如果没有则使用本地数据
const effectiveWeatherData = computed(() => {
  return props.weatherData || WeatherData.value
})

const IPData = ref({})
const WeatherData = ref({})
const option = ref({})

// 获取指定日期是周几
function getWeekDay(date) {
  // 如果传入的是字符串，转换为Date对象
  const dateObj = typeof date === 'string' ? new Date(date) : date
  // 获取今天的日期（只保留年月日）
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  // 获取明天的日期
  const tomorrow = new Date(today)
  tomorrow.setDate(tomorrow.getDate() + 1)

  // 获取传入日期（只保留年月日）
  const targetDate = new Date(dateObj)
  targetDate.setHours(0, 0, 0, 0)

  // 比较日期
  if (targetDate.getTime() === today.getTime()) {
    return '今天'
  } else if (targetDate.getTime() === tomorrow.getTime()) {
    return '明天'
  } else {
    // 星期几数组
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
    // 获取星期几（0-6，0表示周日）
    const dayIndex = dateObj.getDay()

    return weekdays[dayIndex]
  }
}

const processWeatherData = computed(() => {
  if (
    effectiveWeatherData.value &&
    effectiveWeatherData.value.forecasts &&
    effectiveWeatherData.value.forecasts.length > 0 &&
    effectiveWeatherData.value.forecasts[0].casts
  ) {
    return effectiveWeatherData.value.forecasts[0].casts.map((item, index) => ({
      day: getWeekDay(item.date),
      date: item.date,
      condition: item.dayweather,
      wind: item.daypower,
      daytemp: item.daytemp,
      nighttemp: item.nighttemp,
    }))
  }
})

const renderChart = () => {
  // 准备图表数据
  let xAxisData = []
  let dayTempData = []
  let nightTempData = []

  const weatherData = processWeatherData.value
  if (weatherData && weatherData.length > 0) {
    xAxisData = weatherData.map((item) => item.day)
    dayTempData = weatherData.map((item, index) => ({
      value: parseFloat(item.daytemp),
      label: { show: true },
    }))
    nightTempData = weatherData.map((item, index) => ({
      value: parseFloat(item.nighttemp),
      label: { show: true },
    }))
  }

  // 计算温度范围，用于设置y轴
  const allTemps = [
    ...dayTempData.map((item) => item.value),
    ...nightTempData.map((item) => item.value),
  ]
  const minTemp = Math.min(...allTemps)
  const maxTemp = Math.max(...allTemps)

  // 扩大温度范围以增加线条间隔的视觉效果
  const expandedMin = Math.floor(minTemp) - 3
  const expandedMax = Math.ceil(maxTemp) + 3
  option.value = {
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 78, 113, 0.8)',
      borderColor: '#004e71',
      textStyle: {
        color: '#ffffff',
      },
      formatter: function (params) {
        let result = params[0].name + '<br/>'
        params.forEach((param) => {
          result +=
            param.marker + param.seriesName + ': ' + param.value + '°C<br/>'
        })
        return result
      },
    },

    grid: {
      left: '8%',
      right: '12%',
      bottom: '15%',
      top: '15%',
      containLabel: true,
    },

    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,

      show: false,
      axisLine: {
        lineStyle: {
          color: '#ffffff',
        },
      },
      axisLabel: {
        color: '#ffffff',
      },
      axisTick: {
        lineStyle: {
          color: '#ffffff',
        },
      },
    },
    yAxis: {
      type: 'value',
      show: false,
      min: expandedMin, // 扩大范围
      max: expandedMax, // 扩大范围
      interval: 5,
      axisLine: {
        lineStyle: {
          color: '#ffffff',
        },
      },
      axisLabel: {
        color: '#ffffff',
        formatter: '{value}°C',
      },
      splitLine: {
        lineStyle: {
          color: 'rgba(255, 255, 255, 0.2)',
        },
      },
    },
    series: [
      {
        name: '白天温度',
        type: 'line',
        data: dayTempData,

        showSymbol: true,
        symbolSize: 5,
        lineStyle: {
          width: 1.5,
          color: '#ff9900', // 橙色表示白天
        },
        itemStyle: {
          color: '#ff9900',
        },
        label: {
          show: true,
          position: 'top',
          color: '#ffffff',
          fontSize: 12,
          formatter: function (params) {
            return '白' + params.value + '°C'
          },
        },
      },
      {
        name: '夜间温度',
        type: 'line',
        data: nightTempData,

        showSymbol: true,
        symbolSize: 5,
        lineStyle: {
          width: 3,
          color: '#4a90e2', // 蓝色表示夜间
        },
        itemStyle: {
          color: '#4a90e2',
        },
        label: {
          show: true,
          position: 'bottom',
          fontSize: 12,
          color: '#ffffff',
          formatter: function (params) {
            return '晚' + params.value + '°C'
          },
        },
      },
    ],
  }
}

// 监听effectiveWeatherData的变化，重新渲染图表
watch(effectiveWeatherData, () => {
  renderChart()
})

onMounted(async () => {
  // 只有在没有外部传入数据时才获取本地数据
  if (!props.weatherData) {
    IPData.value = await getIPData()
    WeatherData.value = await getWeatherData(IPData.value.adcode, 'all')
  }
  renderChart()
})
</script>

<style scoped>
.weather-container {
  margin-top: 0.5rem;
  padding: 2.5rem 3rem;
  background-color: rgb(0, 78, 113);

  border-radius: 0.25rem;
  .weather-info {
    display: flex;
    gap: 1.5rem;
    div {
      display: flex;
      gap: 1rem;
      flex-direction: column;
      flex: 1 1 0%;
      text-align: center;
    }
  }
  .weather-chart {
    height: 10rem;
    margin-top: 2.5rem;
  }
}
</style>
